package com.nutricia.core.service.impl;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nutricia.common.dal.persistant.SystemRole;
import com.nutricia.common.util.CheckUtil;
import com.nutricia.core.ex.BizErrorCode;
import com.nutricia.core.ex.BizException;
import com.nutricia.core.model.domain.SystemRoleDO;
import com.nutricia.core.service.SystemRoleService;
import com.nutricia.core.service.convertor.SystemRoleServiceConvertor;

/**
 * 系统角色serviceImpl
 *
 * @author: huangsheng
 * @date: 2017/10/19
 */
@Service("systemRoleService")
public class SystemRoleServiceImpl extends AbstractServiceImpl implements SystemRoleService {

    /**
     * 获取角色数据
     *
     * @author: huangsheng
     * @date: 2017/10/24 上午10:44
     */
    @Override
    public List<SystemRoleDO> getSystemRoles() {

        return SystemRoleServiceConvertor.convertToSystemRoleDOs(systemRoleMapper.queryRole());
    }

    /**
     * 新建角色
     *
     * @return 新建的角色ID
     * @author: huangsheng
     * @date: 2017/10/26 上午11:03
     */
    @Override
    public String createSystemRole(SystemRoleDO systemRoleDO) {
        int roleCodeCount = systemRoleMapper.checkRoleCode(systemRoleDO.getRoleCode());
        logger.info("查询到 roleCode = {}， 的数量在库里是 {}", systemRoleDO.getRoleCode(), roleCodeCount);
        CheckUtil.isTrue(roleCodeCount == 0, BizErrorCode.ROLE_CODE_IS_EXIST, BizErrorCode.ROLE_CODE_IS_EXIST.getDescription());

        try {
            SystemRole systemRole = new SystemRole();
            String uuid = UUID.randomUUID().toString();
            logger.info("准备创建角色，ID = {}", uuid);
            systemRole.setId(uuid);
            systemRole.setRoleCode(systemRoleDO.getRoleCode());
            systemRole.setRoleName(systemRoleDO.getRoleName());
            int successInsertCount = systemRoleMapper.insertRole(systemRole);
            logger.info("成功插入 {} 条数据", successInsertCount);
            return uuid;
        } catch (Exception e) {
            logger.error("创建角色时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 更新角色数据
     *
     * @author: huangsheng
     * @date: 2017/10/26 上午11:33
     */
    @Override
    public void updateSystemRole(SystemRoleDO systemRoleDO) {

        SystemRole systemRole = systemRoleMapper.queryRoleByRoleId(systemRoleDO.getId());
        CheckUtil.isTrue(null != systemRole, BizErrorCode.ROLE_IS_NOE_EXIST, BizErrorCode.ROLE_IS_NOE_EXIST.getDescription());
        logger.info("查询到角色数据： roleCode = {}", systemRole.getRoleCode());
        if (!StringUtils.equals(systemRole.getRoleCode(), systemRoleDO.getRoleCode())) {
            int roleCodeCount = systemRoleMapper.checkRoleCode(systemRoleDO.getRoleCode());
            logger.info("查询到 roleCode = {}， 的数量在库里是 {}", systemRoleDO.getRoleCode(), roleCodeCount);
            CheckUtil.isTrue(roleCodeCount == 0, BizErrorCode.ROLE_CODE_IS_EXIST, BizErrorCode.ROLE_CODE_IS_EXIST.getDescription());
        }
        try {
            logger.info("准备修改角色，ID = {}", systemRoleDO.getId());
            SystemRole updateSystemRole = new SystemRole();
            updateSystemRole.setId(systemRoleDO.getId());
            updateSystemRole.setRoleCode(systemRoleDO.getRoleCode());
            updateSystemRole.setRoleName(systemRoleDO.getRoleName());

            int successUpdateCount = systemRoleMapper.updateSystemRole(updateSystemRole);
            logger.info("成功执行 {} 条数据", successUpdateCount);
        } catch (Exception e) {
            logger.error("修改角色时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 删除角色数据
     *
     * @author: huangsheng
     * @date: 2017/10/26 上午11:33
     */
    @Override
    public void deleteSystemRole(String roleId) {
        try {
            logger.info("逻辑删除 ID = {} 的角色数据", roleId);
            int successDeleteCount = systemRoleMapper.deleteSystemRole(roleId);
            logger.info("成功执行 {} 条数据", successDeleteCount);
        } catch (Exception e) {
            logger.error("删除角色时异常：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }

    /**
     * 保存角色权限
     *
     * @param roleId        角色ID
     * @param permissionIds 权限ID集合
     */
    @Transactional
    @Override
    public void saveRolePermission(String roleId, List<String> permissionIds) {
        try {
            int i = rolePermissionMapper.deletePermissionByRoleId(roleId);
            logger.info("成功执行删除：{}", i);
            rolePermissionMapper.batchInsertRolePermission(roleId, permissionIds);
            logger.info("批量插入{}条数据", permissionIds.size());
        } catch (Exception e) {
            logger.error("保存角色权限：{}", e);
            throw new BizException(BizErrorCode.SYSTEM_ERROR, "系统异常");
        }
    }
}
